// JavaScript Document

/**
 * import compontent 
 */
Vsg.importClass(
	[
		"Vsg.DataSourceEntity.DataSourceEntityBuilder",
		"Vsg.EntityRecord.StockTopAssembly"	
	]
);

Vsg.loadExtLibs([
	"ux/RowExpander.js"
	]
);


/**
 * this method using by parent window ,defined the global
 */
function getSelectedCategoryRecords() {
	var panels = [
		Ext.getCmp('statCycleSpots'),
		Ext.getCmp('newSpots'),
		Ext.getCmp('todaySpots')
	]
	var recs = [];
	for (var i = 0 ; i < panels.length ; i++) {
		var selModel = panels[i].getSelectionModel();
		var urlStrArray = panels[i].getStore().proxy.url.split("/");

		var selRecs = selModel.getSelections();
		for (var j = 0 ; j < selRecs.length ; j++) {
			var data = selRecs[j].data;
			data["startDate"] = urlStrArray[0];
			data["cycle"] = (urlStrArray[2] = urlStrArray[2] == null || urlStrArray[2]=='' ? 1:urlStrArray[2] ) ;
			recs.push(data);
		}
	}
	return recs;
}


function getCategoryChartsPanel(title , id , params) {
	try {
		
		var d = new Date();
		var dStr = d.format('Y-m-d');
		var resturl = dStr;
		if (params) {
			resturl = resturl + "/"+params.cycle + "/" + params.chartsCycle;
		}
		resturl +="/"+UrlMKey['stk-assembly-charts-list'];

		var $dsEntity = new Vsg.DataSourceEntity.DataSourceEntityBuilder();
		$dsEntity.setUrl(resturl);
		$dsEntity.setEntityRecord( new Vsg.EntityRecord.StockTopAssembly() );

		var $ds = $dsEntity.newLoadedDataSource({
			autoload:true
		});

		var sm = new Ext.grid.CheckboxSelectionModel({
			singleSelect:false
		});
	
		// --- defined the grid panel ---
   		var grid = new Ext.grid.GridPanel({
        	store: $ds,
			id:id,
			sm:sm,			
			maskDisabled:false,
        	loadMask: true,
			title:title,        	
        	// grid columns
			colModel:new Ext.grid.ColumnModel([
				sm,
				{
					header: "描 述",
					width: 150,
					sortable: false,
					dataIndex: "description"
				},
				{
					header: "出现次数",
					width: 50,
					sortable: true, 
					dataIndex: "count"
				},
				{
					header: "类 型",
					width: 70,
					sortable: true, 
					dataIndex: "type"
				}								
			]),
        	// customize view config
        	viewConfig: {
            	forceFit:true
        	},			
        	stripeRows: true

    	});

		grid.on("rowclick" , Vsg.getDefinedEvent("SpotsPanel.evt_rowclick"));		
		
		return grid;	
	} catch (e) {
		alert("Get model panel error: "  );
	}
}

function getCateDateListPanel(url) {
	
	var store = new Ext.data.JsonStore({
    	// store configs
    	autoLoad : false,
    	url: url,
    	storeId: 'cateDateListStore',
    	// reader configs
    	root: 'rows',
    	idProperty: 'showId',  
    	fields: [
			{name:'cateDate'},
			{name:'interval', type: 'int'},
			{name:'rate', type: 'float'}
		]
	});
	
	try {
		// --- grid panel ---
  		var grid = new Ext.grid.GridPanel({
        	store: store,
			id:'stkCateAssemblyDailyPanel',			
			maskDisabled:false,
        	loadMask: true,        	
        	// grid columns
			colModel:new Ext.grid.ColumnModel([
				{
					header: "日 期",
					width: 100,
					sortable: false,
					renderer:function(val) {
						return val;
					},
					dataIndex: "cateDate"
				},
				{
					header: "平均涨幅",
					sortable: false, 
					dataIndex: "rate"
				},
				{
					header: "与上次间隔",
					sortable: false, 
					dataIndex: "interval"
				}								
			]),
        	// customize view config
        	viewConfig: {
            	forceFit:true
        	},			
        	stripeRows: true

    	});
		grid.on("rowclick" , Vsg.getDefinedEvent("DateList.evt_rowclick"));				
		return grid;	
	} catch (e) {
		alert("Get model panel error: ");
	}
}


function getCateAssemblyStockPanel(url) {
    var expander = new Ext.ux.grid.RowExpander({
        tpl : new Ext.Template(
            '<p><b>关联种类/板块:</b> {assemblyCates}</p>',
			'<p><b>出现日期:</b> {assemblyDates}</p>'
        )
    });

	var store = new Ext.data.JsonStore({
    	// store configs
    	autoLoad : false,
    	url: url,
    	storeId: 'cateStockStore',
    	// reader configs
    	root: 'rows',
    	idProperty: 'stkCode',  
    	fields: [
			{name:'stockCode'},
			{name:'stockName'},
			{name:'rate', type: 'float'},
			{name:'assemblyCates', type:'string'},
			{name:'assemblyDates', type:'string'}
		]
	});
	
	try {
		// --- grid panel ---
  		var grid = new Ext.grid.GridPanel({
        	store: store,
			id:'stkCateAssemblyStkPanel',			
			maskDisabled:false,
        	loadMask: true,        	
        	// grid columns
			colModel:new Ext.grid.ColumnModel([
				expander,
				{
					header: "股票代码",
					width: 100,
					sortable: false,
					dataIndex: "stockCode"
				},
				{
					header: "股票名称",
					sortable: false, 
					dataIndex: "stockName"
				},
				{
					header: "涨 幅",
					sortable: false, 
					dataIndex: "rate",
					renderer:function(val) {
						var result = (val*100).toFixed(2);
						return result+"%";
					}
				}								
			]),
        	// customize view config
        	viewConfig: {
            	forceFit:true
        	},
			plugins: expander,		
        	stripeRows: true

    	});
	
		return grid;	
	} catch (e) {
		alert("Get model panel error: ");
	}	
}

/** ===============================
 * init ui interface 
 * ================================
 */
function init(){

	try {
		
		// --- set layout content -----
		var $layoutContent = {
			layout:"border",
			items:[
				{
					region:'north',
					height:430,	
					layout:'fit',
					margins:"5 5 5 5 ",
					border:false,
					items:[
						{
							xtype:'panel',
							layout: 'column',
							tbar:[{
            					text:'指定日期：'
        					},{
                    			xtype: 'datefield',
                    			id: 'dateDefined',
								value:(new Date().format('Y-m-d')),
								format:'Y-m-d',
								allowBlank:false,
                    			selectOnFocus: true,
                    			width: 80
                    		},' ', {
            					text:'统计周期(天)：'
        					},{
                    			xtype: 'numberfield',
                    			id: 'statCycle',
								allowBlank:false,
								value:'30',
                    			selectOnFocus: true,
                    			width: 20
                    		},' ',
							{
            					text:'上榜周期(天)：'
        					},{
                    			xtype: 'numberfield',
                    			id: 'getInCharts',
								value:'20',
								allowBlank:false,
                    			selectOnFocus: true,
                    			width: 20
                    		},' ',
							{
            					text:'新上榜周期(天)：'
        					},{
                    			xtype: 'numberfield',
                    			id: 'newGetinCharts',
								value:'3',
								allowBlank:false,
                    			selectOnFocus: true,
                    			width: 20
                    		},' ',{
								iconCls:'bmenu',
								text:'刷 选',
								handler:Vsg.getDefinedEvent('catelist.evt_click')
							}
							],
							items:[
							{
								region:'west',
								columnWidth: 0.3333,
								layout:'fit',
								bodyStyle:'padding:5px 0px 5px 5px',
								border:false,
								height:400,								
								items:[getCategoryChartsPanel('上榜热点','statCycleSpots',{cycle:30,chartsCycle:20})]
							},{
								columnWidth: 0.3333,
								bodyStyle:'padding:5px 5px 5px 5px',
								border:false,
								height:400,								
								layout:'fit',
								items:[getCategoryChartsPanel('新热点','newSpots',{cycle:20,chartsCycle:5})]
							},{
								columnWidth: 0.3333,
								bodyStyle:'padding:5px 5px 5px 0px',
								border:false,
								height:400,								
								layout:'fit',
								items:[getCategoryChartsPanel('指定当天热点','todaySpots')]
							}							
							]
						}
					]
				},
				{
					region:'center',
					layout:'fit',
					border:false,
					margins:"0 5 5 5",
					items:[
					{
						xtype:'panel',
						layout:'border',
						title:'热点分布情况',
						items:[{
							region:'west',
							width: 300,
							margins:"5 0 5 5",
							border:false,
							layout:'fit',
							split:true,
							items:[getCateDateListPanel(UrlMKey['stk-assembly-charts-datelist'])]
						},{
							region:'center',
							margins:"5 5 5 0",
							border:false,
							layout:'fit',
							items:[getCateAssemblyStockPanel(UrlMKey['stk-assembly-charts-stocklist'])]						
						}]						
					}
					]
				}
			]
		};

    	new Ext.Viewport( $layoutContent );
	} catch (e) {
		alert('出现系统性错误，请联系管理人员!');
	}
	
	
	// ---- extend handle event ---- 
	
		
}
// --- run the init method
Vsg.run( init );


/**
 *  defined row click 
 * @param {Object} $this
 * @param {Object} rowIndex
 * @param {Object} event
 */
Vsg.definedEvent("SpotsPanel.evt_rowclick" , function($this, rowIndex, event) {

	var panels = [
		Ext.getCmp('statCycleSpots'),
		Ext.getCmp('newSpots'),
		Ext.getCmp('todaySpots')
	]
	var panel = $this;
	for (var i = 0 ; i < panels.length ; i++) {
		if ($this != panels[i]) {
			// --- set unselect model ---
			var selModel = panels[i].getSelectionModel();
			selModel.clearSelections();
		} 
	}
	// --- get the record description ---
	var rec = $this.getStore().getAt(rowIndex);
	var cateDesc = rec.get("description");



	// --- reload the other panel ---
	var stkCateAssemblyDailyPanel = Ext.getCmp("stkCateAssemblyDailyPanel");
	var dailyPanelStore = stkCateAssemblyDailyPanel.getStore();

	var proxyUrl = panel.getStore().proxy.url;
	var patternUrlArray = proxyUrl.split("/");
	var cycle = patternUrlArray[2] ? patternUrlArray[2]:1; // set default cycle
	var resturl = patternUrlArray[0] + "/"+cycle + "/" + UrlMKey['stk-assembly-charts-datelist'];
	
	dailyPanelStore.proxy = new Ext.data.ScriptTagProxy({
			url:resturl
	});
	
	dailyPanelStore.removeAll();
	dailyPanelStore.setBaseParam('cateDesc',encodeURI(cateDesc));
	dailyPanelStore.load();
	
	var stkCateAssemblyStkPanel = Ext.getCmp("stkCateAssemblyStkPanel");
	stkCateAssemblyStkPanel.getStore().removeAll();
	
});


Vsg.definedEvent("DateList.evt_rowclick" , function($this, rowIndex, event) {

	var stkCateAssemblyDailyPanel = Ext.getCmp("stkCateAssemblyDailyPanel");
	var dailyPanelStore = stkCateAssemblyDailyPanel.getStore();
	
	var refDate = dailyPanelStore.getAt(rowIndex).get("cateDate");
	
	var proxyUrl = dailyPanelStore.proxy.url;
	var patternUrlArray = proxyUrl.split("/");
	var resturl = refDate + "/"+patternUrlArray[1]+"/"+UrlMKey['stk-assembly-charts-stocklist'] ;

	var stkCateAssemblyStkPanel = Ext.getCmp("stkCateAssemblyStkPanel");
	var stkCateAssemStore = stkCateAssemblyStkPanel.getStore();
	stkCateAssemStore.proxy = new Ext.data.ScriptTagProxy({
			url:resturl
	});
	stkCateAssemStore.removeAll();
	for (var i in dailyPanelStore.baseParams) {
		stkCateAssemStore.setBaseParam(i, dailyPanelStore.baseParams[i]);
	}
	//
	stkCateAssemStore.load();



});

/**
 *  defined row click 
 * @param {Object} $this
 * @param {Object} rowIndex
 * @param {Object} event
 */
Vsg.definedEvent("catelist.evt_click" , function($this, event) {
	
	var refDate = Ext.getCmp("dateDefined").getValue();
	var statCycle = Ext.getCmp("statCycle").getValue();
	var getInCharts = Ext.getCmp("getInCharts").getValue();
	var newGetinCharts = Ext.getCmp("newGetinCharts").getValue();
	
	
	// --- defined value date build the defined url ---
	var statCycleSpotsPanel = Ext.getCmp("statCycleSpots");
	var newSpotsPanel = Ext.getCmp("newSpots");
	var todaySpotsPanel = Ext.getCmp("todaySpots");

	var statCycleSpotsStore = statCycleSpotsPanel.getStore();
	var newSpotsStore = newSpotsPanel.getStore();
	var todaySpotsStore = todaySpotsPanel.getStore();
	
	statCycleSpotsStore.on("beforeload",function($this) {
		var lastIndx = $this.proxy.url.lastIndexOf("/");
		var patternUrl = $this.proxy.url.substring(lastIndx);
		
		var dStr = refDate.format('Y-m-d');
		var resturl = dStr + "/"+statCycle + "/" + getInCharts+patternUrl;
		
		$this.proxy = new Ext.data.ScriptTagProxy({
			url:resturl
		});
	})
	
	statCycleSpotsStore.removeAll();
	statCycleSpotsStore.load();
	

	newSpotsStore.on("beforeload",function($this) {
		var lastIndx = $this.proxy.url.lastIndexOf("/");
		var patternUrl = $this.proxy.url.substring(lastIndx);
		
		var dStr = refDate.format('Y-m-d');
		var resturl = dStr + "/"+statCycle + "/" + newGetinCharts+patternUrl;
		
		$this.proxy = new Ext.data.ScriptTagProxy({
			url:resturl
		});
	})
	
	newSpotsStore.removeAll();
	newSpotsStore.load();	


	todaySpotsStore.on("beforeload",function($this) {
		var lastIndx = $this.proxy.url.lastIndexOf("/");
		var patternUrl = $this.proxy.url.substring(lastIndx);
		
		var dStr = refDate.format('Y-m-d');
		var resturl = dStr + patternUrl;
		
		$this.proxy = new Ext.data.ScriptTagProxy({
			url:resturl
		});
	})
	
	todaySpotsStore.removeAll();
	todaySpotsStore.load();	
	
});

